﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using FinalProject.Entities;

namespace FinalProject.Web.ViewModels
{
    public class CreateUserViewModel
    {
        public virtual int UserId { get; set; }
        public virtual string Comment { get; set; }
        public virtual string Email { get; set; }
        public virtual string Password { get; set; }
        public virtual string UserName { get; set; }

        public virtual List<AssignedUserRole> UserRoles { get; set; }

        public virtual int CompanyId { get; set; }
        public virtual List<Company> Companies { get; set; }

        public CreateUserViewModel()
        {
            UserRoles = new List<AssignedUserRole>();
        }

        public CreateUserViewModel(User user)
        {
            UserRoles = new List<AssignedUserRole>();
            Comment = user.Comment;
            Email = user.Email;
            Password = user.Password;
            UserName = user.UserName;
            UserId = user.Id;
        }

        public void InitializeAssignedUserRoles(List<UserRole> allUserRoles, List<UserRole> currentUserRoles)
        {
            var existingRoles = new HashSet<int>(currentUserRoles.Select(r => r.Id));
            foreach(var role in allUserRoles)
            {
                this.UserRoles.Add(
                    new AssignedUserRole
                    {
                        UserRoleId = role.Id,
                        UserRoleName = role.Name,
                        Assigned = existingRoles.Contains(role.Id)
                    });
            }
        }

        public List<UserRole> ConvertAssignedRolesToUserRoles()
        {
            var roles = new List<UserRole>();
            foreach (var role in this.UserRoles)
            {
                if (role.Assigned)
                    roles.Add(new UserRole { Id = role.UserRoleId });
            }
            return roles;
        }
    }
}